/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.framework.common.enums.CommonStatus;
import com.easy.framework.common.exception.ServiceException;
import com.easy.framework.common.model.TreeModel;
import com.easy.framework.common.utils.ConvertUtil;
import com.easy.framework.common.utils.Func;
import com.easy.framework.common.utils.SpringUtils;
import com.easy.framework.common.utils.StringUtil;
import com.easy.framework.security.annotation.DataScope;
import com.easy.framework.security.utils.SecurityUtils;
import com.easy.module.system.entity.SysDept;
import com.easy.module.system.enums.DeptType;
import com.easy.module.system.mapper.SysDeptMapper;
import com.easy.module.system.query.SysDeptQuery;
import com.easy.module.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 部门表 Service业务
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-19
 */
@RequiredArgsConstructor
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {


    /**
     * 获取查询对象
     *
     * @param query
     * @return
     */
    @Override
    public LambdaQueryWrapper<SysDept> lambdaQuery(SysDeptQuery query) {
        Optional<LambdaQueryWrapper<SysDept>> optional = lambdaQueryOptional(query);
        optional.ifPresent(w -> w.apply(Func.isNotEmpty(query.getDataScope()), query.getDataScope()));
        return optional.orElse(null);
    }

    /**
     * 查询部门管理数据
     *
     * @param query 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "sys_dept",deptIdName = "id")
    public List<SysDept> queryList(SysDeptQuery query) {
        return list(lambdaQuery(query));
    }

    /**
     * 新增部门
     *
     * @param dto 部门
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(SysDept dto) {
        SysDept entity = ConvertUtil.convert(dto, SysDept.class);
        if (Func.isNotEmpty(entity.getParentId())) {
            SysDept info = getById(entity.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!CommonStatus.enabled.getValue().equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
            Long orgId = getOrgId(info.getId());
            entity.setOrgId(orgId);
            entity.setAncestors(info.getAncestors() + "," + entity.getParentId());
        } else {
            entity.setParentId(0L);
            entity.setOrgId(entity.getId());
            entity.setAncestors("0");
        }
        return save(entity);
    }


    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = list(lambdaQueryWrapper().apply("find_in_set({0}, ancestors)", deptId));
        if (Func.isNotEmpty(children)) {
            for (SysDept child : children) {
                child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            }
            baseMapper.updateDeptChildren(children);
        }
    }


    /**
     * 修改该部门的父级部门状态
     *
     * @param dto 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dto) {
        String ancestors = dto.getAncestors();
        Long[] deptIds = ConvertUtil.toLongArray(ancestors);
        SysDept dept = new SysDept();
        dept.setStatus(CommonStatus.enabled.getValue());
        update(dept, Wrappers.<SysDept>lambdaUpdate().in(SysDept::getId, deptIds));
    }

    /**
     * 修改部门
     *
     * @param dept 部门
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysDept dept) {
        SysDept newParentDept = getById(dept.getParentId());
        if (Func.isEmpty(dept.getParentId())) {
        }
        if (Func.isNotEmpty(dept.getParentId()) && !dept.getParentId().equals(dept.getParentId())) {
            Long orgId = getOrgId(newParentDept.getId());
            dept.setOrgId(orgId);
        }
        SysDept oldDept = getById(dept.getId());
        if (Func.isNotEmpty(newParentDept) && Func.isNotEmpty(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getId(), newAncestors, oldAncestors);
        }
        if ((dept.getParentId().equals(0L)) || (DeptType.DEPT.getValue().equals(oldDept.getDeptType()) && DeptType.ORG.getValue().equals(dept.getDeptType()))) {
            //是顶级部门或部门变机构
            baseMapper.updateDeptChildrenOrgId(oldDept.getOrgId(), dept.getId(), dept.getId());
        } else if (DeptType.ORG.getValue().equals(oldDept.getDeptType()) && DeptType.DEPT.getValue().equals(dept.getDeptType())) {
            //机构变部门
            Long orgId = getOrgId(newParentDept.getId());
            dept.setOrgId(orgId);
            baseMapper.updateDeptChildrenOrgId(oldDept.getOrgId(), orgId, dept.getId());
        }
        SysDept entity = ConvertUtil.convert(dept, SysDept.class);
        boolean result = updateById(entity);
        if (CommonStatus.enabled.getValue().equals(dept.getStatus()) && Func.isNotEmpty(dept.getAncestors())
                && !StringUtil.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 删除部门信息
     *
     * @param deptId 部门主键
     * @return 结果
     */
    @Override
    public boolean deleteById(Long deptId) {
        return removeById(deptId);
    }

    /**
     * 获取部门机构号
     *
     * @param list
     * @param deptId
     * @return
     */
    @Override
    public Long getOrgId(List<SysDept> list, Long deptId) {
        if (Func.isNotEmpty(list)) {
            SysDept dept = list.stream().filter(p -> deptId.equals(p.getId())).findFirst().orElse(null);
            if (dept != null) {
                if (DeptType.ORG.getValue().equals(dept.getDeptType()) || null == dept.getParentId() || dept.getParentId() < 1) {
                    return dept.getId();
                }
                return getOrgId(list, dept.getParentId());
            }
        }
        return 0L;
    }

    /**
     * 获取部门机构号
     *
     * @param deptId
     * @return
     */
    @Override
    public Long getOrgId(Long deptId) {
        return getOrgId(list(), deptId);
    }

    @Override
    public List<SysDept> children(SysDeptQuery query) {
        List<SysDept> menuList = SpringUtils.getAopProxy(this).queryList(query);
        if (Func.isNotEmpty(menuList)) {
            menuList.forEach(d -> {
                d.setHasChildren(count(lambdaQueryWrapper().eq(SysDept::getParentId, d.getId())) > 0);
            });
        }
        return menuList;
    }

    @Override
    public List<TreeModel> treeList(List<SysDept> list) {
        List<TreeModel> treeModelList = new ArrayList<>();
        if (Func.isNotEmpty(list)) {
            List<Long> tempList = list.stream().map(SysDept::getId).collect(Collectors.toList());
            for (SysDept dept : list) {
                // 如果是顶级节点, 遍历该父节点的所有子节点
                if (!tempList.contains(dept.getParentId())) {
                    treeModelList.add(new TreeModel(dept.getId(), dept.getDeptName(), childDept(list, dept.getId())));
                }
            }
        }
        return treeModelList;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    private List<TreeModel> childDept(List<SysDept> deptList, Long parentId) {
        List<TreeModel> childList = new ArrayList<TreeModel>();
        List<SysDept> tempList = deptList.stream().filter(d -> parentId.equals(d.getParentId())).collect(Collectors.toList());
        if (Func.isNotEmpty(tempList)) {
            for (SysDept dept : tempList) {
                childList.add(new TreeModel(dept.getId(), dept.getDeptName(), childDept(deptList, dept.getId())));
            }
        }
        return childList;
    }


    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void validateDataScope(Long deptId) {
        if (!SecurityUtils.isAdmin()) {
            SysDeptQuery dept = new SysDeptQuery();
            dept.setId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).queryList(dept);
            if (Func.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }


    /**
     * 根据ID查询所有启用状态的子部门
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public Long getEnabledChildDeptCountById(Long deptId) {
        return count(lambdaQueryWrapper()
                .eq(SysDept::getStatus, CommonStatus.enabled.getValue())
                .apply(" find_in_set({0},ancestors)", deptId));
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return count(lambdaQueryWrapper()
                .apply(" find_in_set({0},ancestors)", deptId))>0;
    }
}
